package tool

import (
	"bufio"
	"github.com/op/go-logging"
	"net"
	"strings"
)

var servLogger *logging.Logger = logging.MustGetLogger("server")

type Server struct {
	listener   net.Listener
	addr       string
	credential string

	// 上游代理
	upstream *UpstreamProxy
}

func NewServer(addr string, upstream *UpstreamProxy) *Server {
	return &Server{
		addr:     addr,
		upstream: upstream,
		//credential: base64.StdEncoding.EncodeToString([]byte("123:123")),
	}
}

func (s *Server) Start() {
	var err error
	s.listener, err = net.Listen("tcp", s.addr)
	if err != nil {
		servLogger.Fatal(err)
	}

	if s.credential != "" {
		servLogger.Infof("use %s for auth\n", s.credential)
	}
	servLogger.Infof("proxy listen in %s, waiting for connection...\n", s.addr)

	for {
		conn, err := s.listener.Accept()
		if err != nil {
			servLogger.Error(err)
			continue
		}
		go s.newConn(conn).serve()
	}
}

func (s *Server) newConn(conn net.Conn) *Conn {
	println(conn)
	logging.SetFormatter(format)
	return &Conn{
		s,
		conn,
		bufio.NewReader(conn),
	}
}

func (s *Server) isAuth() bool {
	return s.credential != ""
}

// validateCredentials parse "Basic basic-credentials" and validate it
func (s *Server) validateCredential(basicCredential string) bool {
	c := strings.Split(basicCredential, " ")
	if len(c) == 2 && strings.EqualFold(c[0], "Basic") && c[1] == s.credential {
		return true
	}
	return false
}
